package io.renren.modules.avanotes.service.impl;

import com.hankcs.hanlp.seg.common.Term;
import com.hankcs.hanlp.tokenizer.IndexTokenizer;
import io.renren.common.utils.RedisUtils;
import io.renren.config.BizConfig;
import io.renren.modules.avanotes.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: xiaomi
 * @date: 2022/1/28
 * @description:
 */
@Service(BizConfig.IMPL_TOKENIZER_INDEX)
public class IndexTokenizerServiceImpl implements TokenService {


    @Autowired
    RedisUtils redisUtils;

    /**
     * 过滤掉词性：
     * w 标点
     * nx 字母专名
     * uj 助词
     *
     * @param uid     数据的唯一性
     * @param content 数据内容
     */
    @Override
    public void save(String uid, String content) {
        List<Term> termList = IndexTokenizer.segment(content);
        Map<String, Object> map = new HashMap<>();
        //组合成 String:index1,index2,index3...
        for (Term term : termList) {
            String na = term.nature.toString();
            if ("w".equals(na) || "nx".equals(na) || "uj".equals(na)) {
                continue;
            }
            String key = term.word;
            String tValue = term.offset + "";
            if (map.containsKey(key)) {
                String concat = map.get(key).toString().concat(",").concat(tValue);
                map.put(key, concat);
            } else {
                map.put(key, tValue);
            }
        }
        redisUtils.hMSet(uid, map);
    }

    @Override
    public List<Integer> searchTokenIndex(String uid, String token) {
        List<Integer> res = new ArrayList<>();
        String resp = redisUtils.hGet(uid, token);
        if (StringUtils.isEmpty(resp)) {
            return res;
        }
        String[] strings = resp.split(",");
        for (String string : strings) {
            res.add(Integer.parseInt(string));
        }
        return res;
    }
}
